package service

import (
	"singo/model"
	"singo/serializer"
	"strings"
	"time"
)

// DemandUpdateService 更新需求的服务
type DemandUpdateService struct {
	ID         string   `form:"id" json:"id" binding:"required"`
	Name       string   `form:"name" json:"name"`
	Intro      string   `form:"intro" json:"intro"`
	Status     uint     `form:"status" json:"status"`
	Priority   uint     `form:"priority" json:"priority"`
	Progress   int      `form:"progress" json:"progress"`
	ExecuteBy  []string `form:"execute_by" json:"execute_by"`
	StartAt    string   `form:"start_at" json:"start_at"`
	CompleteAt string   `form:"complete_at" json:"complete_at"`
	DeadlineAt string   `form:"deadline_at" json:"deadline_at"`
}

// DemandUpdate 更新需求
func (service *DemandUpdateService) DemandUpdate() *serializer.Response {
	var demand model.Demand
	err := model.DB.First(&demand, "uid = ?", service.ID).Error
	if err != nil {
		return &serializer.Response{
			Status: 404,
			Msg:    "不存在",
			Error:  err.Error(),
		}
	}

	if service.StartAt != "" {
		startAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.StartAt, time.Local)
		demand.StartAt = &startAt
	} else {
		demand.StartAt = nil
	}

	if service.DeadlineAt != "" {
		deadlineAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.DeadlineAt, time.Local)
		demand.DeadlineAt = &deadlineAt
	} else {
		demand.DeadlineAt = nil
	}

	if len(service.ExecuteBy) != 0 {
		excuteUser := strings.Join(service.ExecuteBy, ",")
		demand.ExecuteBy = excuteUser
	} else {
		demand.ExecuteBy = ""
	}

	if service.Progress == 100 || service.Status == 3 {
		demand.Progress = 100
		demand.Status = 3
		completeAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.CompleteAt, time.Local)
		demand.CompleteAt = &completeAt
	} else {
		demand.Status = service.Status
		demand.Progress = service.Progress
		demand.CompleteAt = nil
	}

	demand.Name = service.Name
	demand.Intro = service.Intro
	demand.Priority = service.Priority
	if err = model.DB.Save(&demand).Where("uid = ?", service.ID).Error; err != nil {
		return &serializer.Response{
			Status: 50002,
			Msg:    "需求任务保存失败",
			Error:  err.Error(),
		}
	}

	return &serializer.Response{
		Data:   true,
		Msg:    "成功",
		Status: 0,
	}
}
